//
//  UIImage+SampleBuffer.m
//  CaptureDemo
//
//  Created by 苏沫离 on 2018/9/19.
//  Copyright © 2018年 苏沫离. All rights reserved.
//

#import "UIImage+SampleBuffer.h"

@implementation UIImage (SampleBuffer)

//从样本缓冲区数据创建UIImage
+ (UIImage *)imageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer
{
    //为媒体数据获取CMSampleBuffer的核心视频图像缓冲区
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    //锁定像素缓冲区的基地址
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    
    //获取像素缓冲区每行的字节数
    void * baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
    
    //获取像素缓冲区每行的字节数
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    //获取像素缓冲区的宽度和高度
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    
    //创建依赖于设备的RGB颜色空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    //使用样本缓冲区数据创建位图图形上下文
    CGContextRef context = CGBitmapContextCreate(baseAddress,width,height,8,
    bytesPerRow,colorSpace,kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    //根据位图图形上下文中的像素数据创建Quartz图像
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    //解锁像素缓冲区
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    //释放上下文和颜色空间
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    //从Quartz图像创建图像对象
    UIImage *image = [UIImage imageWithCGImage:quartzImage];

    //释放Quartz图像
    CGImageRelease(quartzImage);

    return image;
}
@end
